package com.fm.service;


import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.fm.core.core.SelectAction;


@Slf4j
public class Service {

    public static final int TCP_Port = 18888;

    /**
     * 用来接收序号的并建立连接
     *
     * @throws IOException
     */
    public static void StartTCPServer() throws IOException {
        // 监听端口
        ServerSocket ss = new ServerSocket(TCP_Port);
        log.info("服务运行在端口: " + TCP_Port);

        // 线程池 避免频繁地创建和销毁线程
        ExecutorService executorService = Executors.newFixedThreadPool(100);

        // 时刻等待客户端连接
        while (true) {

            //等待连接
            Socket socket = ss.accept();

            log.info("客户端 - 新服务 - 已连接...");

            //添加到线程池管理生命周期
            executorService.submit(new Thread(() -> {
                log.info(" ##### 线程名: " + Thread.currentThread().getName() + " 已启动!");
                String s;
                //获取任务序号
                try {
                    byte[] bytes = new byte[1024];
                    int read = socket.getInputStream().read(bytes, 0, 1);
                    s = new String(bytes, 0, 1);
                    // log.info(s);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                // 根据选项做出动作 中心选择
                // log.info("中转: "+s);
                SelectAction(s, socket);

            }));
        }

    }


}
